using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Collections.Specialized;
using System.Web;

namespace CKS.WindowsLiveAuthentication
{
    public class LiveMembershipProvider : MembershipProvider
    {
        protected string appName;

        public override string ApplicationName
        {
            get { return appName; }
            set {  }
        }

        public override bool EnablePasswordReset
        {
            get { return false; }
        }


        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }


        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }


        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }


        public override int MaxInvalidPasswordAttempts
        {
            get { return 4; }
        }


        public override int PasswordAttemptWindow
        {
            get { return 5; }
        }


        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Clear; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 1; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 1; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return ""; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (name == null || name.Length == 0)
            {
                name = "LiveMembershipProvider";
            }

            appName = name;

            // Initialize the abstract base class.
            base.Initialize(name, config);
        }

        public override bool ChangePassword(string username, string oldPwd, string newPwd)
        {
            return false;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username,
              string password,
              string newPwdQuestion,
              string newPwdAnswer)
        {
            return false;
        }

        /// <summary>
        /// This will create a user profile in our blog site, we can use a config setting
        /// to determine if multiple blogs use the same users.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="email"></param>
        /// <param name="passwordQuestion"></param>
        /// <param name="passwordAnswer"></param>
        /// <param name="isApproved"></param>
        /// <param name="providerUserKey"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (BlogUserProfile.CreateUser(username, email))
            {
                MembershipUser user = GetUser(username, true);
                status = MembershipCreateStatus.Success;
                return user;
            }
            else
            {
                status = MembershipCreateStatus.ProviderError;
                throw new Exception("The user could not be created.");
            }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            BlogUserProfile bup = BlogUserProfile.GetUser(providerUserKey.ToString());
            MembershipUser user = new MembershipUser(ApplicationName, bup.Id, bup.Id, bup.Email, "", "", bup.Approved, bup.Locked, bup.Created, bup.LastLogin, bup.LastLogin, DateTime.Now, bup.LockedOn);
            return user;
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            BlogUserProfile bup = BlogUserProfile.GetUser(username);
            MembershipUser user = new MembershipUser(ApplicationName, bup.Id, bup.Id, bup.Email, "", "", bup.Approved, bup.Locked, bup.Created, bup.LastLogin, bup.LastLogin, DateTime.Now, bup.LockedOn);
            return user;
        }

        public override string GetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override bool ValidateUser(string username, string password)
        {
            BlogUserProfile bup = BlogUserProfile.GetUser(username);

            return (bup != null && password == "04943027183766352ae979e75b991d63");
        }

        public override bool UnlockUser(string userName)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override string GetUserNameByEmail(string email)
        {
            BlogUserProfile[] bup = BlogUserProfile.GetUsersByTag(email, "Email");

            if (bup != null)
            {
                return bup[0].Id;
            }
            else
            {
                return string.Empty;
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection col = new MembershipUserCollection();

            foreach (BlogUserProfile bup in BlogUserProfile.GetAllUsers())
            {
                col.Add(new MembershipUser(ApplicationName, bup.Id, bup.Id, bup.Email, "", "", bup.Approved, bup.Locked, bup.Created, bup.LastLogin, bup.LastLogin, DateTime.Now, bup.LockedOn));
            }

            totalRecords = col.Count;
            return col;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection col = new MembershipUserCollection();

            foreach (BlogUserProfile bup in BlogUserProfile.GetUsersByTag(usernameToMatch, "Title"))
            {
                col.Add(new MembershipUser(ApplicationName, bup.Id, bup.Id, bup.Email, "", "", bup.Approved, bup.Locked, bup.Created, bup.LastLogin, bup.LastLogin, DateTime.Now, bup.LockedOn));
            }

            totalRecords = col.Count;
            return col;
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection col = new MembershipUserCollection();

            foreach (BlogUserProfile bup in BlogUserProfile.GetUsersByTag(emailToMatch, "Email"))
            {
                col.Add(new MembershipUser(ApplicationName, bup.Id, bup.Id, bup.Email, "", "", bup.Approved, bup.Locked, bup.Created, bup.LastLogin, bup.LastLogin, DateTime.Now, bup.LockedOn));
            }

            totalRecords = col.Count;
            return col;
        }
    }
}
